/**
 * 版权所有(C)，上海勾芒信息科技，2017，所有权利保留。
 * 
 * 项目名：	cards-web
 * 文件名：	RsAppServiceImpl.java
 * 模块说明：	
 * 修改历史：
 * 2017年4月21日 - Debenson - 创建。
 */
package com.alex.insistence.rest.app.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;

import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alex.insistence.rest.app.RsAppService;
import com.alex.insistence.rest.common.MyExceptionCode;
import com.alex.wechat.app.account.entity.WxAppAccountEntity;
import com.alex.wechat.app.account.service.WxAppAccountServiceI;
import com.alex.wechat.app.config.WxAppContext;
import com.gomore.jeecg.common.Assert;
import com.gomore.jeecg.common.ServiceException;

import cn.binarywang.wx.miniapp.api.WxMaServiceEx;

/**
 * @author Debenson
 * @since 0.1
 */
@Service("RsAppServiceImpl")
public class RsAppServiceImpl implements RsAppService {

  public static final String QRCODE_TYPE_QRCODE = "qrcode";
  public static final String QRCODE_TYPE_WXACODE = "wxacode";

  @Autowired
  private WxMaServiceEx wxAppService;
  @Autowired
  private WxAppAccountServiceI wxAppAccountService;

  @Override
  public Response createQrCode(String tenantId, String path, int size, String type, String storeId)
      throws ServiceException {
    Assert.assertArgumentNotEmpty(tenantId, "tenantId");
    Assert.assertArgumentNotEmpty(path, "path");

    initWxAccount(tenantId);
    try {
      File file = null;

      String destPath = path;
      if (StringUtils.isNotEmpty(storeId)) {
        destPath += String.format("?storeId=%s", storeId);
      }

      if (Objects.equals(QRCODE_TYPE_WXACODE, type)) {
        file = wxAppService.getQrcodeServiceEx().createWxacode(destPath);
      } else {
        file = wxAppService.getQrcodeServiceEx().createQrcode(destPath, size);
      }
      return Response.ok(IOUtils.toByteArray(new FileInputStream(file)), "image/webp").build();
    } catch (Exception e) {
      throw new ServiceException(e);
    }
  }

  private void initWxAccount(String tenantId) throws ServiceException {
    WxAppAccountEntity account = wxAppAccountService.getAccountByParterId(tenantId);
    if (account == null) {
      throw new ServiceException(MyExceptionCode.wxAppAccountNotFound);
    }
    WxAppContext.setAppId(account.getAppId());
  }

}
